package com.ghsc.ghxc.jsb.ui.main.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ActivityUtils
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.databinding.FragmentPwVersionBinding
import com.ghsc.ghxc.jsb.ui.bean.VersionDataBean
import com.maning.updatelibrary.InstallUtils
import java.io.File
import java.io.FileInputStream


/**
 * 版本升级
 */
class VersionFragment  : BaseVMFragment<VersionViewModel, FragmentPwVersionBinding>(R.layout.fragment_pw_version) {

   private var sysBean : VersionDataBean?=null
    companion object {
        fun newInstance(sysBean : VersionDataBean): VersionFragment {
            val fragment = VersionFragment()
            fragment.sysBean= sysBean
            return fragment
        }
    }

    override fun attachVMClass(): Class<VersionViewModel>? {
      return VersionViewModel::class.java
    }

    override fun lazyLoad() {
    }



    //弹框关闭回调
    private var dismiss:(() -> Unit)? = null
    fun setOnDismissListener(listener: (() -> Unit)){
        this.dismiss = listener
    }


    private val  activity = ActivityUtils.getTopActivity() as AppCompatActivity
    override fun initView(savedInstanceState: Bundle?) {

        initCallBack()
        sysBean?.let {
            //版本
            binding.tvEdition.text="更新内容 v"+it.version
            //更新说明
            binding.tvMemo.text=it.memo
            //强制更新
            if (it.ifmust==1) {
                binding.tvSure.visibility = View.VISIBLE
                binding.llPb.visibility = View.GONE
                binding.imgSureNo.visibility = View.GONE
            } else {
                binding.tvSure.visibility = View.VISIBLE
                binding.llPb.visibility = View.GONE
                binding.imgSureNo.visibility = View.VISIBLE
            }

            loge("下载链接="+it.url)

        }

    }


    override fun initClickListener() {
        super.initClickListener()
        binding.imgSureNo.setSingleClickListener {
            dismiss?.invoke()
        }
        binding.tvSure.setSingleClickListener {
            //立即更新
            if (sysBean==null) return@setSingleClickListener
            binding.tvSure.visibility = View.GONE
            binding.llPb.visibility = View.VISIBLE
            InstallUtils.with(activity) //必须-下载地址
                .setApkUrl(sysBean!!.url) //                            //非必须-下载保存的文件的完整路径+name.apk
                //                            .setApkPath(Constants.APK_SAVE_PATH)
                //非必须-下载回调
                .setCallBack(downloadCallBack) //开始下载
                .startDownload()
        }

        binding.tvInstall.setSingleClickListener {
            //安装
            if (sysBean==null) return@setSingleClickListener
            loge("安装地址=="+apkDownloadPath)
            if (TextUtils.isEmpty(apkDownloadPath)){
                InstallUtils.with(activity) //必须-下载地址
                    .setApkUrl(sysBean!!.url) //                            //非必须-下载保存的文件的完整路径+name.apk
                    //                            .setApkPath(Constants.APK_SAVE_PATH)
                    //非必须-下载回调
                    .setCallBack(downloadCallBack) //开始下载
                    .startDownload()
            }else
                installApk(apkDownloadPath!!)
        }
    }


    private var downloadCallBack: InstallUtils.DownloadCallBack? = null
    private var apkDownloadPath: String? = null
    //下载apk的回调
    private fun initCallBack() {
        downloadCallBack = object : InstallUtils.DownloadCallBack {
            override fun onStart() {
                binding.tvProgress.text="0 %"
            }
            override fun onComplete(path: String) {
//                LoggerUtils.e("InstallUtils---onComplete:$path")

                //获取文件大小
                val file = File(path)
                val fileSizes = getFileSizes(file)
                //APK大于1MB
                if (fileSizes <= 1 * 1024 * 1024) {
//                    LoggerUtils.e("文件异常，请稍后重试:$fileSizes")
                }
                apkDownloadPath = path
                binding.tvProgress.text="100 %"
                //去安装APK
                installApk(apkDownloadPath!!)
                binding.tvSure.visibility=View.GONE
                binding.llPb.visibility=View.GONE
                binding.tvInstall.visibility= View.VISIBLE
            }

            override fun onLoading(total: Long, current: Long) {
                //内部做了处理，onLoading 进度转回progress必须是+1，防止频率过快
                val progress = (current * 100 / total).toInt()
                binding.tvProgress.text= "$progress %"
                binding.pbVoteOne.progress=progress
            }

            override fun onFail(e: Exception) {
                binding.tvSure.visibility= View.VISIBLE
                binding.tvSure.text = "重新下载"
                binding.llPb.visibility= View.GONE
            }

            override fun cancle() {
            }
        }
    }

    private fun installApk(path: String) {
        InstallUtils.installAPK(activity, path, object : InstallUtils.InstallCallBack {
            override fun onSuccess() {
                //onSuccess：表示系统的安装界面被打开
                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                showToast("正在安装程序")
            }

            override fun onFail(e: Exception) {
//                tv_info.setText("安装失败:" + e.toString());
                binding.tvSure.visibility= View.VISIBLE
                binding.tvSure.text = "重新下载"
                binding.llPb.visibility= View.GONE
            }
        })
    }

    fun getFileSizes(f: File): Long {
        return try {
            var s: Long = 0
            if (f.exists()) {
                var fis: FileInputStream? = null
                fis = FileInputStream(f)
                s = fis.available().toLong()
                fis.close()
            }
            s
        } catch (e: Exception) {
            0
        }
    }
}